<?php
/**
 * Created by PhpStorm.
 * User: ChengChaogui
 * Date: 2016/11/30
 * Time: 14:41
 */

namespace App\Framework\Helper;

use App\Framework\Config\SystemConstant;
use App\Framework\Model\Message;
use OSS\OssClient;
use URL;

class UploadHelper
{
    private static $ossClient = null;
    private static $image_ext = array('jpg', 'jpeg', 'gif', 'png');

    //创建阿里云oss客户端
    public static function getOssClient()
    {
        if (self::$ossClient == null) {
            self::$ossClient = new OssClient(SystemConstant::OSS_ACCESS_KEY_ID, SystemConstant::OSS_ACCESS_KEY_SECRET, SystemConstant::OSS_END_POINT);
        }

        return self::$ossClient;
    }

    public static function uploadImageToOss($image)
    {
        $resultMsg = self::uploadImage($image);
        if ($resultMsg->fail) {
            return $resultMsg;
        }

        $ossClient = self::getOssClient();
        $pos = strripos($resultMsg->value, '/');
        $fileName = substr($resultMsg->value, $pos + 1);
        $ossObject = 'images/' . $fileName;
        $savePath = ltrim($resultMsg->value, '/');
        $ossClient->uploadFile(SystemConstant::OSS_BUCKET, $ossObject, public_path($savePath));
        unlink(public_path($savePath));
        return Message::setTrue('上传成功', SystemConstant::OSS_OUTER_URL . $ossObject);
    }


    public static function uploadImage($image)
    {
        $file_size = round($image->getSize() / (1024 * 1024));
        if ($file_size > 2) {
            return Message::setFalse('图片大小不能超过2M');
        }

        $file_ex = strtolower($image->getClientOriginalExtension());
        if (in_array($file_ex, SystemConstant::IMAGE_FORMAT) == false) {
            return Message::setFalse('不支持该种格式的图片');
        }
        //图片存放目录
        $save_dir = str_replace('\\', '/', public_path('upload\images\\'));
        //生成唯一文件名
        $newname = TextHelper::getUuid() . '.' . $file_ex;
        //将文件移动到指定目录
        $image->move($save_dir, $newname);
        return Message::setTrue('上传成功', '/upload/images/' . $newname);
    }

}


